package co.th.bjc.md.helper;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import co.th.bjc.md.common.ConnectDB;
import co.th.bjc.md.model.Category;

public class CategoryHelper {

private static Logger _log = Logger.getLogger(CategoryHelper.class);
	
	public List<Category> findAllCategory() throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		List<Category> listCategory = new ArrayList<Category>(0);
		ConnectDB connectDB = null;
		try{
			String sql = "SELECT * FROM category ";
			_log.info("SQL : " + sql);
			
			connectDB = new ConnectDB();
			conn = connectDB.getConnection();
			stmt = conn.prepareStatement(sql);
			
			rs = stmt.executeQuery();
			while (rs.next()){
				listCategory.add(this.setCategory(rs));
			}
		}catch(Exception ex){
			_log.error("findAllCategory --> " + ex.toString());
			ex.printStackTrace();
		}finally{
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			connectDB.close();
		}
		return listCategory;
	}

	public Category findCategoryByCategoryCode(BigDecimal categoryCode) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Category category = null;
		ConnectDB connectDB = null;
		try{
			String sql = "SELECT * FROM category WHERE category_id = ?";
			_log.info("SQL : " + sql);
			
			connectDB = new ConnectDB();
			conn = connectDB.getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setBigDecimal(1, categoryCode);
			
			rs = stmt.executeQuery();
			if (rs.next()){
				category = this.setCategory(rs);
			}
		}catch(Exception ex){
			_log.error("findCategoryByCategoryCode --> " + ex.toString());
			ex.printStackTrace();
		}finally{
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			connectDB.close();
		}
		return category;
	}
	
	private Category setCategory(ResultSet rs) throws Exception{
		Category category = new Category();
		category.setCategoryCode(rs.getBigDecimal("category_id"));
		category.setCategoryNameTh(rs.getString("category_name_th"));
		category.setCategoryNameEn(rs.getString("category_name_en"));
		category.setCreateBy(rs.getString("create_by"));
		category.setCreateDate(rs.getDate("create_date"));
		category.setUpdateBy(rs.getString("update_by"));
		category.setUpdateDate(rs.getDate("update_date"));
		return category;
	}
}
